package cn.edu.njuit.server.ugcnote.ugcnoteserver.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@EnableWebSecurity
public class SecurityConfiguration {
    @Autowired
    JwtApiFilter jwtApiFilter;
    @Bean
    public PasswordEncoder passwordEncoder() {
        /**
         * 指定密码加密模式：加盐哈希加密
         */
        return new BCryptPasswordEncoder();
    }
    @Bean
    SecurityFilterChain filterChain(HttpSecurity http)throws Exception{
        return http.csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                //过滤接口
                .antMatchers("/api/open/**").permitAll()
                .antMatchers("/api/regist").permitAll()
                .antMatchers("/api/login").permitAll()
                .antMatchers("/api/**").authenticated()
                .and()
                .addFilterBefore(jwtApiFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }
}
